// mmo_game_server/social/auction_house_impl.go
package social

import (
    "errors"
    "log"
    "sync"
    "your_project/data"
)

// AuctionHouse 拍卖行系统
type AuctionHouse struct {
    items    map[int64]*AuctionItem
    mu       sync.Mutex
    db       *data.DB
}

// AuctionItem 拍卖物品
type AuctionItem struct {
    ID          int64
    SellerID    int64
    ItemID      int64
    Price       int64
    EndTime     int64
    HighestBid  int64
    HighestBidder int64
}

// NewAuctionHouse 创建新的拍卖行
func NewAuctionHouse(db *data.DB) *AuctionHouse {
    return &AuctionHouse{
        items: make(map[int64]*AuctionItem),
        db:    db,
    }
}

// ListItem 上架物品
func (ah *AuctionHouse) ListItem(sellerID, itemID, price, endTime int64) (int64, error) {
    ah.mu.Lock()
    defer ah.mu.Unlock()
    // 生成物品ID
    itemID = int64(len(ah.items) + 1)
    item := &AuctionItem{
        ID:          itemID,
        SellerID:    sellerID,
        ItemID:      itemID,
        Price:       price,
        EndTime:     endTime,
        HighestBid:  0,
        HighestBidder: 0,
    }
    ah.items[itemID] = item
    // 保存到数据库
    _, err := ah.db.Exec("INSERT INTO auction_items (seller_id, item_id, price, end_time) VALUES ($1, $2, $3, $4)", sellerID, itemID, price, endTime)
    if err != nil {
        log.Printf("Failed to list item in auction house: %v", err)
        return 0, err
    }
    return itemID, nil
}

// PlaceBid 竞拍物品
func (ah *AuctionHouse) PlaceBid(bidderID, itemID, bidAmount int64) error {
    ah.mu.Lock()
    defer ah.mu.Unlock()
    item, ok := ah.items[itemID]
    if!ok {
        return errors.New("item not found")
    }
    if bidAmount <= item.HighestBid {
        return errors.New("bid amount must be higher than current highest bid")
    }
    item.HighestBid = bidAmount
    item.HighestBidder = bidderID
    // 更新数据库
    _, err := ah.db.Exec("UPDATE auction_items SET highest_bid = $1, highest_bidder = $2 WHERE id = $3", bidAmount, bidderID, itemID)
    if err != nil {
        log.Printf("Failed to place bid in auction house: %v", err)
        return err
    }
    return nil
}

// EndAuction 结束拍卖
func (ah *AuctionHouse) EndAuction(itemID int64) error {
    ah.mu.Lock()
    defer ah.mu.Unlock()
    item, ok := ah.items[itemID]
    if!ok {
        return errors.New("item not found")
    }
    // 处理成交逻辑
    if item.HighestBid > 0 {
        // 给卖家转账
        // 给买家发放物品
    }
    delete(ah.items, itemID)
    // 从数据库删除
    _, err := ah.db.Exec("DELETE FROM auction_items WHERE id = $1", itemID)
    if err != nil {
        log.Printf("Failed to end auction in auction house: %v", err)
        return err
    }
    return nil
}